<template>
  <div class="view-account">
    <div class="view-account-header"></div>
    <div class="view-account-container">
      <div class="view-account-top">
        <div class="view-account-top-logo">
          <img src="~@/assets/images/account-logo.png" alt="" />
        </div>
        <div class="view-account-top-desc">Naive Ui Admin中台前端/设计解决方案</div>
      </div>
      <div class="view-account-form">
        <span style="display: block; font-weight: bold; font-size: 16px; margin-bottom: 2vh"
          >绑定账号</span
        >
        <n-form
          ref="formRef"
          label-placement="left"
          size="large"
          :model="formInline"
          :rules="formRules"
        >
          <n-form-item path="username">
            <n-input v-model:value="formInline.username" placeholder="请输入用户名">
              <template #prefix>
                <n-icon size="18" color="#808695">
                  <PersonOutline />
                </n-icon>
              </template>
            </n-input>
          </n-form-item>
          <n-form-item path="password">
            <n-input
              v-model:value="formInline.password"
              type="password"
              show-password-toggle
              placeholder="请输入密码"
            >
              <template #prefix>
                <n-icon size="18" color="#808695">
                  <LockClosedOutline />
                </n-icon>
              </template>
            </n-input>
          </n-form-item>
          <n-form-item path="isCaptcha">
            <div class="w-full">
              <mi-captcha width="384" theme-color="#2d8cf0" :logo="logo" @success="onAuthCode" />
            </div>
          </n-form-item>
        </n-form>
        <n-grid :cols="1">
          <n-gi :span="1">
            <n-button
              type="primary"
              size="large"
              block
              @click="submitRelate()"
              :loading="loading"
              :disabled="loading"
            >
              <span v-if="!loading">绑定</span>
              <span v-else>绑定中</span>
            </n-button>
          </n-gi>
        </n-grid>
        <router-link to="/login">
          <n-button text type="info">
            <template #icon>
              <n-icon>
                <ArrowBackOutline />
              </n-icon>
            </template>
            返回
          </n-button>
        </router-link>
      </div>
    </div>
  </div>
</template>
<script>
  import { defineComponent, ref, reactive, onMounted } from 'vue';
  import {
    PersonOutline,
    LockClosedOutline,
    ArrowBackOutline,
    MailOutline,
  } from '@vicons/ionicons5';
  import { useMessage } from 'naive-ui';
  import { useRouter, useRoute } from 'vue-router';
  import logo from '@/assets/images/logo.png';
  import { useUserStore } from '@/store/modules/user';
  import { relate, getToken } from '../../api/system/social';
  import { storage } from '@/utils/Storage';
  import { ACCESS_TOKEN, CURRENT_USER, IS_LOCKSCREEN } from '../../store/mutation-types';
  export default defineComponent({
    name: 'FindPwd',
    components: {
      PersonOutline,
      LockClosedOutline,
      MailOutline,
      ArrowBackOutline,
    },
    setup() {
      const formInline = reactive({
        username: '',
        password: '',
        isCaptcha: false,
        id: '',
        socialType: null,
        isLogin: false,
      });
      const router = useRouter();
      const route = useRoute();
      const flag = ref(true);
      const userStore = useUserStore();
      const btnDisabled = ref(false);
      const message = useMessage();
      const loading = ref(false);
      const formRef = ref();
      const formRules = {
        username: { required: true, message: '请输入用户名', trigger: 'blur' },
        password: { required: true, message: '请输入密码', trigger: 'blur' },
        isCaptcha: {
          required: true,
          type: 'boolean',
          trigger: 'change',
          message: '请点击按钮进行验证码校验',
          validator: (_, value) => value === true,
        },
      };
      const onAuthCode = () => {
        formInline.isCaptcha = true;
      };
      const submitRelate = () => {
        if (formInline.id == '') {
          message.error('参数错误');
          return;
        }
        formInline.isLogin = false;
        formRef.value.validate(async (errors) => {
          if (!errors) {
            message.loading('绑定中...');
            loading.value = true;
            relateSubmit();
          } else {
            loading.value = false;
            message.error('请填写完整信息，并且进行验证码校验');
          }
        });
      };
      const relateSubmit = () => {
        relate(formInline).then((res) => {
          let tokenKey = res;
          getToken(tokenKey).then((data) => {
            const ex = 7 * 24 * 60 * 60 * 1000;
            storage.set(ACCESS_TOKEN, data, ex);
            storage.set(CURRENT_USER, data, ex);
            storage.set(IS_LOCKSCREEN, false);
            userStore.setToken(data);
            const toPath = decodeURIComponent(route.query?.redirect || '/');
            message.success('登录成功！');
            router.replace(toPath).then((_) => {
              if (route.name == 'login') {
                router.replace('/');
              }
            });
          });
        });
      };
      function initRelate() {
        let userInfo = userStore.getUserInfo;
        console.log(Object.keys(userInfo).length);
        if (Object.keys(userInfo).length > 0) {
          relateDirect();
        }
      }
      const relateDirect = () => {
        formInline.isLogin = true;
        relate(formInline).then((res) => {
          if (res) {
            message.success('绑定成功');
            router.push({ name: 'setting-account', query: { type: 'social' } });
          }
        });
      };
      onMounted(() => {
        let id = route.query.id;
        let socialType = route.query.socialType;
        formInline.id = id;
        formInline.socialType = socialType;
        initRelate();
      });
      return {
        formInline,
        btnDisabled,
        formRules,
        loading,
        formRef,
        logo,
        submitRelate,
        onAuthCode,
      };
    },
  });
</script>

<style lang="less" scoped>
  .view-account {
    display: flex;
    flex-direction: column;
    height: 100vh;
    overflow: auto;

    &-container {
      flex: 1;
      padding: 32px 0;
      width: 384px;
      margin: 0 auto;
    }

    &-top {
      padding: 32px 0;
      text-align: center;

      &-desc {
        font-size: 14px;
        color: #808695;
      }
    }

    &-other {
      width: 100%;
    }

    .default-color {
      color: #515a6e;

      .ant-checkbox-wrapper {
        color: #515a6e;
      }
    }
  }

  @media (min-width: 768px) {
    .view-account {
      background-image: url('../../assets/images/login.svg');
      background-repeat: no-repeat;
      background-position: 50%;
      background-size: 100%;
    }

    .page-account-container {
      padding: 32px 0 24px 0;
    }
  }
</style>
